﻿package com.dykj.platform.framework.utils;

import com.dykj.platform.framework.exception.ApplicationException;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.FatalBeanException;

/**
 * @Title: DYKJ Platform
 * @Description: Bean拷贝
 * @Copyright: Copyright (c) 2008
 * @Company: DYKJ
 * @author jit@dykj.cn
 * @version 1.0
 */
public class BeanUtils {

	protected static Log log = LogFactory.getLog(BeanUtils.class);

	private BeanUtils() {
	}

	/**
	 * Bean的拷贝，转化小写。
	 * 
	 * @param dest
	 * @param orig
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	public static void copyPropertiesLowerCase(Object dest, Object orig)
			throws IllegalAccessException, InvocationTargetException {
		if (dest == null)
			throw new IllegalArgumentException("No destination bean specified");
		if (orig == null)
			return;
		if (log.isDebugEnabled())
			log.debug("BeanUtils.copyProperties(" + dest + ", " + orig + ")");
		if (orig instanceof Map) {
			for (Iterator names = ((Map) orig).keySet().iterator(); names
					.hasNext();) {
				String name = ((String) names.next()).toLowerCase();
				if (BeanUtilsBean.getInstance().getPropertyUtils().isWriteable(
						dest, name)) {
					Object value = ((Map) orig).get(name);
					if (value != null)
						copyPropertyLowerCase(dest, name, value);
				}
			}

		} else {
			PropertyDescriptor origDescriptors[] = BeanUtilsBean.getInstance()
					.getPropertyUtils().getPropertyDescriptors(orig);
			for (int i = 0; i < origDescriptors.length; i++) {
				String name = origDescriptors[i].getName().toLowerCase();
				if (!"class".equals(name)
						&& BeanUtilsBean.getInstance().getPropertyUtils()
								.isReadable(orig, name)
						&& BeanUtilsBean.getInstance().getPropertyUtils()
								.isWriteable(dest, name))
					try {
						Object value = BeanUtilsBean.getInstance()
								.getPropertyUtils().getSimpleProperty(orig,
										name);
						if (value != null)
							copyPropertyLowerCase(dest, name, value);
					} catch (NoSuchMethodException nosuchmethodexception) {
					}
			}

		}
	}

	/**
	 * 属性拷贝，小写转换
	 * 
	 * @param desc
	 * @param name
	 * @param value
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	public static void copyPropertyLowerCase(Object desc, String name,
			Object value) throws IllegalAccessException,
			InvocationTargetException {
		if (name == null) {
			throw new IllegalAccessException("No name specified");
		} else {
			String lowerName = name.toLowerCase();
			BeanUtilsBean.getInstance().copyProperty(desc, lowerName, value);
			return;
		}
	}

	/**
	 * Bean拷贝
	 * 
	 * @param dest
	 *            目标Bean
	 * @param orig
	 *            源Bean
	 */
	public static void copyProperties(Object dest, Object orig) {
		try {
			if ((dest instanceof Map) && !(orig instanceof Map)) {
				if (orig != null)
					((Map) dest).putAll(describe(orig));
			} else {
				//为空值时的拷贝
				org.springframework.beans.BeanUtils.copyProperties(orig, dest);
			}
		} catch (FatalBeanException e) {
			try {
				//不同类型的拷贝
				org.apache.commons.beanutils.BeanUtils.copyProperties(dest,
						orig);
			} catch (Exception e1) {
				log.error(e1);
				e1.printStackTrace();
			}
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
		}
	}

	/**
	 * Map 拷贝到 Bean
	 * 
	 * @param dest
	 * @param orig
	 */
	public static void populate(Object dest, Map orig) {
		try {
			org.apache.commons.beanutils.BeanUtils.populate(dest, orig);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
		}
	}

	/**
	 * Bean 到 Map
	 * 
	 * @param orig
	 * @return
	 */
	public static Map describe(Object orig) {
		Map resultMap = null;
		if (orig == null)
			return new HashMap();
		try {
			if (log.isDebugEnabled())
				log.debug("Describing bean: " + orig.getClass().getName());
			resultMap = new HashMap();
			if (orig instanceof DynaBean) {
				DynaProperty descriptors[] = ((DynaBean) orig).getDynaClass()
						.getDynaProperties();
				for (int i = 0; i < descriptors.length; i++) {
					String name = descriptors[i].getName();
					resultMap.put(name, BeanUtilsBean.getInstance()
							.getProperty(orig, name));
				}

			} else {
				PropertyDescriptor descriptors[] = BeanUtilsBean.getInstance()
						.getPropertyUtils().getPropertyDescriptors(orig);
				for (int i = 0; i < descriptors.length; i++) {
					String name = descriptors[i].getName();
					if (descriptors[i].getReadMethod() != null
							&& !"class".equals(descriptors[i].getName()))
						if (orig.getClass().getDeclaredField(
								descriptors[i].getName()).getType() == java.util.Date.class) {
							Method method = descriptors[i].getReadMethod();
							Date date = (Date) method.invoke(orig,
									new Object[0]);
							if (date != null) {
								SimpleDateFormat sdf = new SimpleDateFormat();
								sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
								resultMap.put(name, sdf.format(date));
							}
						} else {
							resultMap.put(name, BeanUtilsBean.getInstance()
									.getProperty(orig, name));
						}
				}

			}
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
		}
		return resultMap;
	}

	/**
	 * 将 entity list 转换为 map list
	 * 
	 * @param entityList
	 * @return
	 */
	public static List entityList2MapList(List entityList) {
		List mapList = null;
		int size = entityList != null ? entityList.size() : 0;
		Map map = null;
		for (int i = 0; i < size; i++) {
			if (mapList == null)
				mapList = new ArrayList();
			map = describe(entityList.get(i));
			mapList.add(i, map);
		}

		return mapList;
	}

	/**
	 * 将字符串转化为Date类型
	 * 
	 * @param src
	 * @param pattern
	 * @return
	 * @throws ApplicationException
	 */
	public static Date toDate(String src, String pattern)
			throws ApplicationException {
		Date date = null;
		if (src.length() == 0 || src.equals(""))
			src = "19000101";
		if (src.length() == 8)
			pattern = "yyyyMMdd";
		SimpleDateFormat sdf = new SimpleDateFormat();
		sdf.applyPattern(pattern);
		try {
			date = new Date(sdf.parse(src).getTime());
		} catch (ParseException e) {
			throw new ApplicationException(e);
		}
		return date;
	}

	/**
	 * 将字符串转化为Date类型
	 * 
	 * @param src
	 * @return
	 * @throws ApplicationException
	 */
	public static Date toDate(String src) throws ApplicationException {
		return toDate(src, "yyyyMMddHHmmss");
	}

	public static String DatetoString(Date dt, String pattern)
			throws ApplicationException {
		SimpleDateFormat sdf = new SimpleDateFormat();
		sdf.applyPattern(pattern);
		String strDate = sdf.format(dt);
		return strDate;
	}

	/**
	 * 将Date类型转化为字符串
	 * 
	 * @param src
	 * @return
	 * @throws ApplicationException
	 */
	public static String DatetoString(Date dt) throws ApplicationException {
		return DatetoString(dt, "yyyyMMddHHmmss");
	}

	public static void main(String args[]) {
		try {
			toDate("2007-12-12 12:12:12");
		} catch (ApplicationException e) {
			e.printStackTrace();
		}
	}

}
